const express = require('express');
const router = express.Router();
const { Challenge, UserAchievement } = require('../models/Challenge');
const redisClient = require('../server').redisClient;

// 获取所有挑战
router.get('/', async (req, res) => {
  try {
    const cacheKey = 'challenges:all';
    const cached = await redisClient.get(cacheKey);
    
    if (cached) {
      return res.json(JSON.parse(cached));
    }

    const challenges = await Challenge.find({ active: true });
    await redisClient.setEx(cacheKey, 3600, JSON.stringify(challenges));
    
    res.json(challenges);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 更新用户挑战进度
router.post('/:id/progress', async (req, res) => {
  try {
    const { userId, value } = req.body;
    const challenge = await Challenge.findById(req.params.id);
    
    if (!challenge) {
      return res.status(404).json({ error: '挑战不存在' });
    }

    const achievement = await UserAchievement.findOneAndUpdate(
      { userId, challengeId: req.params.id },
      { 
        $inc: { progress: value },
        $set: { 
          completed: { $gte: ['$progress', challenge.targetValue] } 
        }
      },
      { new: true, upsert: true }
    );

    // 清除缓存
    await redisClient.del(`user:${userId}:achievements`);
    
    res.json(achievement);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '进度更新失败' });
  }
});

// 获取用户成就
router.get('/achievements', async (req, res) => {
  try {
    const { userId } = req.query;
    const cacheKey = `user:${userId}:achievements`;
    
    const cached = await redisClient.get(cacheKey);
    if (cached) {
      return res.json(JSON.parse(cached));
    }

    const achievements = await UserAchievement.find({ userId })
      .populate('challengeId');
    
    await redisClient.setEx(cacheKey, 1800, JSON.stringify(achievements));
    
    res.json(achievements);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '获取成就失败' });
  }
});

module.exports = router;